package distributedbank.server;

import java.util.Set;
import java.util.HashSet;

import distributedbank.util.CentsConverter;

/**
 * Represents an account in a bank's branch. All of the methods in this class
 * must be thread-safe, since accounts are shared across multiple threads.
 */
public class Account
{
    private Set<Integer> prevTransactionIds = new HashSet<Integer>();

    private int balance; // balance in cents

    public Account() {
        // default constructor
    }

    public Account( int balance ) {
        this.balance = balance;
    }

    /**
     * Deposits a (possibly negative) amount of money to the account and returns
     * the resulting account balance.
     * 
     * @threadsafe
     */
    public synchronized int deposit( int amount, int transactionId ) {
        synchronized( this ) {
            balance += amount;
            prevTransactionIds.add( transactionId );
            return balance;
        }
    }

    public synchronized int query( int transactionId ) {
        synchronized( this ) {
            prevTransactionIds.add( transactionId );
            return balance;
        }
    }

    /**
     * @return $xxx,xxx.xx
     */
    public String getBalanceInDollarsWithSign() {
        return CentsConverter.getAmountInDollarsWithSign( balance );
    }

    /**
     * @return balance in cents
     */
    public int getBalance() {
        return balance;
    }
}
